package com.wsx.ones.akka.api;

import com.wsx.ones.akka.domian.AkkaRequest;
import com.wsx.ones.akka.domian.AkkaResponse;
import com.wsx.ones.akka.domian.Data;
import com.wsx.ones.akka.domian.Message;
import com.wsx.ones.akka.service.AkkaService;
import com.wsx.ones.status.OnesCode;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author wangshuaixin
 * @Title: com.wsx.ones.akka.api.AkkaApi
 * @Description: TODO
 * @date 2019/05/10
 */
@RestController
@RequestMapping("/akka")
public class AkkaApi implements OnesCode {

    private static final long TIMEOUT = 2000L;

    private static AtomicInteger id = new AtomicInteger(0);


    private AkkaService akkaService;
    public AkkaApi(AkkaService akkaService) {
        this.akkaService = akkaService;
    }


    @GetMapping("/async")
    public DeferredResult<Message> getAsyncNonBlocking() {
        final DeferredResult<Message> result = new DeferredResult<Message>(TIMEOUT);
        CompletableFuture<Message> future = akkaService.async("async-non-blocking", id.incrementAndGet());
        future.whenComplete((r,e) -> {
            if (e != null) {
                result.setErrorResult(e);
            } else {
                result.setResult(r);
            }
        });
        return result;
    }


    @PostMapping("/actor")
    public AkkaResponse actor(@RequestBody AkkaRequest request) {
        Data data = akkaService.actor(request);
        return new AkkaResponse(SUCCESS_CODE).data(data);
    }
}
